package org.jeecg.modules.middle.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manage.entity.CaishuiBusiness;
import org.jeecg.modules.manage.entity.CaishuiChannelBinding;
import org.jeecg.modules.manage.entity.CaishuiMiddleUser;
import org.jeecg.modules.middle.business.mapper.CaishuiBusinessMapper;
import org.jeecg.modules.middle.business.mapper.CaishuiChannelBindingMapper;
import org.jeecg.modules.middle.business.mapper.CaishuiMiddleUserMapper;
import org.jeecg.modules.middle.business.service.ICaishuiMiddleUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: 中台用户表
 * @Author: yfkj
 * @Date:   2023-02-07
 * @Version: V1.0
 */
@Service
public class CaishuiMiddleUserServiceImpl extends ServiceImpl<CaishuiMiddleUserMapper, CaishuiMiddleUser> implements ICaishuiMiddleUserService {

	@Resource
	private CaishuiMiddleUserMapper caishuiMiddleUserMapper;
	@Resource
	private CaishuiBusinessMapper caishuiBusinessMapper;
	//注入feign客户端
	@Resource
	private ISysBaseAPI iSysBaseAPI;


	/**
	 * 外键关联分页查询
	 * @param page
	 * @param queryWrapper
	 * @return
	 */
	@Override
	public IPage<CaishuiMiddleUser> pageMultiTable(IPage<CaishuiMiddleUser> page, QueryWrapper<CaishuiMiddleUser> queryWrapper) {
		return this.baseMapper.pageMultiTable(page, queryWrapper);
	}

	@Override
	public List<CaishuiMiddleUser> selectByMainId(String mainId) {
		return caishuiMiddleUserMapper.selectByMainId(mainId);
	}

	@Override
	@Transactional
	public Result<?> addMiddleUser(CaishuiMiddleUser caishuiMiddleUser) {
		LoginUser loginUser = new LoginUser();
		loginUser.setUsername(caishuiMiddleUser.getPhone());
		loginUser.setRealname(caishuiMiddleUser.getRealname());
		loginUser.setPassword(caishuiMiddleUser.getPassword());
		loginUser.setPhone(caishuiMiddleUser.getPhone());
		loginUser.setNickname(TokenUtils.getLoginUser().getNickname());
		loginUser.setAvatar(TokenUtils.getLoginUser().getAvatar());
		loginUser.setRelTenantIds(TokenUtils.getLoginUser().getRelTenantIds());
		loginUser.setUserType(2);
		loginUser.setMiddleOptAuth(2);
		loginUser.setChannelBusinessId(caishuiMiddleUser.getBusinessId());
		loginUser.setMiddleUserType(caishuiMiddleUser.getMiddleUserType());
		Result result = iSysBaseAPI.addBUser(loginUser);//Feign 调用远程微服务接口
		if(oConvertUtils.isEmpty(result)){
			return Result.error("添加失败！");
		}else if(!result.isSuccess()){
			return Result.error(result.getMessage());
		}else  {
			String userId = result.getResult().toString();//用户ID
			caishuiMiddleUser.setUserId(userId);
			caishuiMiddleUserMapper.insert(caishuiMiddleUser);
			return Result.ok("添加成功！");
		}
	}

	@Override
	@Transactional
	public Result<?> editMiddleUser(CaishuiMiddleUser caishuiMiddleUser) {
		LoginUser loginUser = new LoginUser();
		loginUser.setUsername(caishuiMiddleUser.getPhone());
		loginUser.setRealname(caishuiMiddleUser.getRealname());
		loginUser.setPhone(caishuiMiddleUser.getPhone());
		loginUser.setId(caishuiMiddleUser.getUserId());
		loginUser.setUserType(2);
		Result result = iSysBaseAPI.editBUser(loginUser);//Feign 调用远程微服务接口
		if(oConvertUtils.isEmpty(result)){
			return Result.error("编辑失败！");
		}else if(!result.isSuccess()){
			return Result.error(result.getMessage());
		}else  {
			caishuiMiddleUserMapper.updateById(caishuiMiddleUser);
			return Result.ok("编辑成功！");
		}
	}

	/**
	 * 中台用户信息表id（caishui_middle_user）
	 * 或用户表id（sys_user）
	 * @param id
	 * @return
	 */
	@Override
	@Transactional
	public Result<?> deleteMiddleUser(String id) {
		String userId = id;//用户ID
		CaishuiMiddleUser businessUser = caishuiMiddleUserMapper.selectById(id);
		if(oConvertUtils.isNotEmpty(businessUser)){
			userId = businessUser.getUserId();//用户ID
		}

		//判断该用户是否还存在绑定商户
		long b_count = caishuiBusinessMapper.selectCount(new LambdaQueryWrapper<CaishuiBusiness>().eq(CaishuiBusiness::getUserId,userId));
		if (b_count > 0) return Result.error("该用户还存在签约商户，请先移除！");

		//删除中台用户信息
		caishuiMiddleUserMapper.delete(new LambdaQueryWrapper<CaishuiMiddleUser>().eq(CaishuiMiddleUser::getUserId,userId));

		//删除登录用户
		Result result = iSysBaseAPI.deleteBUser(userId);//Feign 调用远程微服务接口
		if(oConvertUtils.isEmpty(result)){
			return Result.error("移除失败！");
		}else if(!result.isSuccess()){
			throw new JeecgBootException(result.getMessage());
			//return Result.error(result.getMessage());
		}
		return Result.ok("删除成功！");
	}
}
